<script setup lang="ts">
import { onMounted, ref, watch, computed } from "vue";
import {
  getDistributionList,
  getDistributionDetail,
  generateBillNo
} from "@/api/orderManag/purchaseOrder";
import { ElMessageBox } from "element-plus";
import { useColumns } from "../utils/columns";
const { fhGoodsColumns } = useColumns();
import { cloneDeep } from "@pureadmin/utils";
import { formRules } from "./utils/rule";
import { message } from "@/utils/message";
import { saveBillNo, destroyBillNo } from "@/utils/express";
import PrintBillNo from "./PrintBillNo.vue";

const props = defineProps({
  subOrderId: {
    type: Number,
    default: 0
  }
});

const deliveryType = ref(1); // 发货商品类型
const submitForm = ref<any>({
  disIndex: null,
  deliveryMethod: 2,
  com: "",
  comName: "",
  generateType: 1,
  generateNum: null
});

const loadDis = ref(false);
const distributionList = ref([]);

const formRef = ref();
const tableSelectList = ref([]);
const loadGoods = ref(false);
const originalGoodsList = ref([]);
const goodsList = ref();
const tableColums = ref(fhGoodsColumns);

// 获取出库单列表
const loadDicList = async () => {
  loadDis.value = true;
  let { data } = await getDistributionList({
    subOrderId: props.subOrderId
  }).catch(() => {
    loadDis.value = false;
  });
  // let data: Array<any> = [
  //   {
  //     distributionCode: "001",
  //     distributionListResponses: [
  //       {
  //         distributionStatus: 1, // 配货出库 1 部分发货 2 全部发货
  //         goodsAmount: 2,
  //         quantityNum: 2
  //       },
  //       {
  //         distributionStatus: 1, // 配货出库 1 部分发货 2 全部发货
  //         goodsAmount: 3,
  //         quantityNum: 3
  //       }
  //     ]
  //   },
  //   {
  //     distributionCode: "002",
  //     distributionListResponses: [
  //       {
  //         distributionStatus: 2, // 配货出库 1 部分发货 2 全部发货
  //         goodsAmount: 3,
  //         quantityNum: 3
  //       },
  //       {
  //         distributionStatus: 2, // 配货出库 1 部分发货 2 全部发货
  //         goodsAmount: 4,
  //         quantityNum: 4
  //       }
  //     ]
  //   }
  // ];
  distributionList.value = data;
  loadDis.value = false;
};

// 获取商品列表
const loadGoodsList = async () => {
  loadGoods.value = true;
  let { data } = await getDistributionDetail({ subOrderId: props.subOrderId });
  goodsList.value = data || [];
  originalGoodsList.value = data || [];
  loadGoods.value = false;
};

const generateTypeChange = () => {
  if (submitForm.value.generateType != 1) {
    submitForm.value.generateNum = "";
  }
};

watch(
  () => submitForm.value.disIndex,
  newIndex => {
    loadGoods.value = true;
    tableSelectList.value = [];
    if (newIndex == undefined) {
      goodsList.value = cloneDeep(originalGoodsList.value);
    } else {
      // 获取商品列表
      let tempList = [];
      if (distributionList.value.length > 0) {
        // 处理商品数据: 从发货商品中里面获取配货商品以及配货数量即可
        let tempDistributionList =
          distributionList.value[newIndex]?.distributionListResponses || [];

        cloneDeep(originalGoodsList.value).forEach(v => {
          let findData = tempDistributionList.find(j => j.goodsId == v.goodsId);
          if (findData && findData.goodsId) {
            v.sendCounts = findData.quantityNum || 0;
            tempList.push(v);
          }
        });
        deliveryType.value =
          tempDistributionList.length > 0
            ? tempDistributionList[0].distributionStatus
            : 1;
      }
      goodsList.value = tempList;
    }

    // 处理表格表头
    if (deliveryType.value == 1) {
      tableColums.value = cloneDeep(fhGoodsColumns);
    } else {
      tableColums.value = cloneDeep(fhGoodsColumns).slice(1, 6);
    }

    setTimeout(() => {
      loadGoods.value = false;
    }, 200);
  }
);

// 承运商
const dataList = JSON.parse(localStorage.getItem("dictList")) || [];
const expressList = computed(() => {
  let key =
    submitForm.value.deliveryMethod == 2
      ? "EXPRES_COMPANY"
      : "LOGISTICS_COMPANY";
  return dataList.find(v => v.dictionaryCode == key).itemList || [];
});

// 更换发货类型
const typeChange = () => {
  loadGoods.value = true;
  tableSelectList.value = [];
  // 处理表格表头
  if (deliveryType.value == 1) {
    tableColums.value = cloneDeep(fhGoodsColumns);
  } else {
    tableColums.value = cloneDeep(fhGoodsColumns).slice(1, 6);
  }

  setTimeout(() => {
    loadGoods.value = false;
  }, 200);
};

// 选择商品
function handleSelectionChange(val) {
  tableSelectList.value = val;
}

onMounted(async () => {
  loadGoodsList();
  loadDicList();
  destroyBillNo(); // 销毁未销毁的运单号
});

// 生成单号
const isCanCreate = ref(true); // 是否可以生成快递号
const billNoLoading = ref(false);
const billNoList = ref([]);
// 是否选择商品且输入发货数量
const isChooseGoods = computed(() => {
  if (deliveryType.value == 2) {
    return true;
  }

  let flag = false;
  if (tableSelectList.value.length > 0) {
    let findData = tableSelectList.value.find(
      v => v.sendCounts && v.sendCounts !== 0
    );
    if (findData) {
      flag = true;
    }
  }
  return flag;
});

const inputFocus = () => {
  if (isCanCreate.value) {
    submitForm.value.generateType = 1;
  }
};

const createBillNo = () => {
  formRef.value.validate(valid => {
    if (!valid) {
      return;
    }
    if (submitForm.value.generateType == 1 && !submitForm.value.generateNum) {
      return message("请输入生成数量", { type: "warning" });
    } else if (submitForm.value.generateType == 2 && deliveryType.value == 1) {
      for (let index = 0; index < tableSelectList.value.length; index++) {
        const v = tableSelectList.value[index];
        if (!v?.sendCounts) {
          message(`'${v.goodsName}' 未填写发货数量`, { type: "warning" });
          return;
        }
      }
    }

    let totalSendCounts = submitForm.value.generateNum;
    if (submitForm.value.generateType == 2) {
      if (deliveryType.value == 1) {
        totalSendCounts = tableSelectList.value
          .map(v => v.sendCounts)
          .reduce((prev, curr) => prev + (curr || 0), 0);
      } else {
        totalSendCounts = goodsList.value
          .map(v => v.goodsAmount)
          .reduce((prev, curr) => prev + (curr || 0), 0);
      }
    }
    let msg =
      submitForm.value.generateType == 3
        ? "是否确认按商品明细条数生成快递单号?"
        : `是否确认生成${totalSendCounts}个快递单号?`;
    ElMessageBox.confirm(msg, "系统提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      dangerouslyUseHTMLString: true,
      draggable: true
    }).then(async () => {
      billNoLoading.value = true;
      let newForm = { ...submitForm.value };
      delete newForm.disIndex;
      newForm.comName = expressList.value.find(
        v => v.itemValue == newForm.com
      ).itemName;
      newForm.generateNum = Number(totalSendCounts);
      newForm.suborderId = props.subOrderId;
      console.log("newForm", newForm);
      generateBillNo(newForm)
        .then(res => {
          console.log("data", res.data);
          saveBillNo({
            subOrderId: props.subOrderId,
            billNoList: res.data || []
          });
          goodsList.value.forEach(v => {
            v.disabled = true;
          });
          billNoList.value = res.data || [];
          isCanCreate.value = false;
          billNoLoading.value = false;
        })
        .catch(() => (billNoLoading.value = false));
    });
  });
};

// 插销单号
const repealBillNo = () => {
  ElMessageBox.confirm("是否确认撤销快递单号?", "系统提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    dangerouslyUseHTMLString: true,
    draggable: true
  }).then(async () => {
    destroyBillNo().then(flag => {
      if (flag) {
        goodsList.value.forEach(v => {
          v.disabled = false;
        });
        billNoList.value = [];
        isCanCreate.value = true;
        message("撤销成功", { type: "success" });
      } else {
        message("撤销异常", { type: "warning" });
      }
    });
  });
};

// 确认发货
const confirmDeliver = () => {
  return new Promise(resolve => {
    let obj: any = {
      isPass: false,
      params: {}
    };
    formRef.value.validate(valid => {
      console.log("valid", valid);
      console.log("valid", goodsList.value);
      if (!valid) {
        resolve(obj);
        return;
      }

      let tempList = tableSelectList.value;
      if (deliveryType.value == 1) {
        // 判断是否填写发货数量
        if (tableSelectList.value.length == 0) {
          message("请选择发货商品", { type: "warning" });
          resolve(obj);
          return;
        }

        for (let index = 0; index < tableSelectList.value.length; index++) {
          const v = tableSelectList.value[index];
          if (!v?.sendCounts) {
            message(`'${v.goodsName}' 未填写发货数量`, { type: "warning" });
            resolve(obj);
            return;
          }
        }
      } else {
        tempList = goodsList.value;
      }

      // 是否生成运单号
      if (billNoList.value.length == 0) {
        message("请生成运单号", { type: "warning" });
        resolve(obj);
        return;
      }

      // 处理数据
      let confirmDeliveryGoodsRequests = tempList.map(v => {
        return {
          deliveryStatus: deliveryType.value,
          goodsId: v.goodsId,
          goodsType: v.goodsType,
          specCode: v.specCode,
          quantityNum: deliveryType.value == 1 ? v.sendCounts : v.goodsAmount
        };
      });

      let comName = expressList.value.find(
        v => v.itemValue == submitForm.value.com
      ).itemName;

      // 发货参数
      obj.params = {
        shippingCategory: 2, // 发货类别 1 供应商发货 2 仓库发货
        suborderId: props.subOrderId,
        num: billNoList.value.map(v => v.kuaidinum),
        storeOrderBillNoRequest: {
          com: submitForm.value.com,
          comName: comName,
          deliveryMethod: submitForm.value.deliveryMethod
        },
        confirmDeliveryGoodsRequests
      };

      if (submitForm.value.disIndex != undefined) {
        obj.params.distributionCode =
          distributionList.value[submitForm.value.disIndex].distributionCode;
      }

      obj.isPass = true;
      console.log("par", obj.params);
      resolve(obj);
    });
  });
};

const printObj = {
  id: "print-box", //打印区域 Dom ID
  popTitle: "商品信息打印",
  extraCss: "https://www.google.com,https://www.google.com",
  extraHead:
    '<meta http-equiv="Content-Language"content="zh-cn"/>,<style>html,body,div{height: auto!important;} #print-box { padding-top: 10px; height: auto !important; } <style>' //  可以传进去  style tag 标签；注意要逗号分隔   解决特定区域不显示问题；
};

defineExpose({ confirmDeliver });
</script>

<template>
  <div class="goods-table">
    <!-- 生成配货出库单 -->
    <div class="mb-5">
      <h3 class="text-black mb-4">生成快递物流单</h3>
      <el-form
        ref="formRef"
        label-position="right"
        label-width="100"
        :model="submitForm"
        :rules="formRules"
        class="w-[360px]"
      >
        <el-form-item label="配货出库单" prop="disIndex">
          <el-select
            v-model="submitForm.disIndex"
            v-loading="loadDis"
            filterable
            clearable
            :disabled="!isCanCreate"
            placeholder="请选择"
          >
            <el-option
              v-for="(item, index) in distributionList"
              :key="index"
              :label="item.distributionCode"
              :value="index"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="发货方式" prop="deliveryMethod">
          <el-radio-group
            v-model="submitForm.deliveryMethod"
            :disabled="!isCanCreate"
            class="ml-4"
            @change="() => (submitForm.com = '')"
          >
            <el-radio :value="2" label="快递" />
            <el-radio :value="1" label="物流" />
          </el-radio-group>
        </el-form-item>
        <el-form-item label="承运商" prop="com">
          <el-select
            v-model="submitForm.com"
            filterable
            placeholder="请选择"
            :disabled="!isCanCreate"
          >
            <el-option
              v-for="(item, index) in expressList"
              :key="index"
              :label="item.itemName"
              :value="item.itemValue"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <!-- 配货出库单 -->
      <div>
        <h3 class="mb-3 text-black">配置发货单</h3>
        <div class="flex items-center justify-between ml-5 mb-3">
          <div class="flex items-center">
            <div>发货商品:</div>
            <!-- 配货出库 1 部分发货 2 全部发货 -->
            <el-radio-group
              v-model="deliveryType"
              :disabled="submitForm.disIndex != undefined || !isCanCreate"
              class="ml-4"
              @change="typeChange"
            >
              <el-radio :value="1" label="部分发货" />
              <el-radio :value="2" label="全部发货" />
            </el-radio-group>
            <!-- <div class="ml-4 font-bold text-orange-400">
              {{ deliveryType == 2 ? "全部发货" : "部分发货" }}
            </div> -->
          </div>
        </div>
        <div class="min-h-[300px] mb-4">
          <div
            v-if="!loadGoods"
            :style="{ width: deliveryType == 1 ? '100%' : '80%' }"
          >
            <pure-table
              row-key="id"
              align-whole="center"
              :header-cell-style="{
                background: 'var(--el-fill-color-light)',
                color: 'var(--el-text-color-primary)'
              }"
              max-height="500"
              :data="goodsList"
              :columns="tableColums"
              @selection-change="handleSelectionChange"
            >
              <template #sendCounts="{ row }">
                <el-input-number
                  v-model="row.sendCounts"
                  class="!w-[135px]"
                  placeholder="请输入"
                  :disabled="!isCanCreate"
                  :precision="0"
                  :min="1"
                  :max="row.goodsAmount || 99999"
                />
              </template>
            </pure-table>
          </div>
        </div>

        <!-- 生成单号 -->
        <div class="ml-5 mb-3">
          <el-tooltip
            content="请选择发货商品且输入发货数量才可生成单号"
            effect="dark"
            placement="top-start"
            :disabled="isChooseGoods"
          >
            <div class="flex items-center mb-3">
              <div class="w-[90px] text-right">生成单号数量</div>
              <!-- 生成类型 1 手动输入 2 按商品数量生成 3 按商品明细条数生成 -->
              <el-radio-group
                v-model="submitForm.generateType"
                class="ml-4"
                :disabled="!isCanCreate || !isChooseGoods"
                @change="generateTypeChange"
              >
                <el-radio :value="1">
                  <div class="flex items-center">
                    <div>生成</div>
                    <el-input
                      v-model="submitForm.generateNum"
                      class="!w-[60px] pl-1 pr-1"
                      :disabled="!isCanCreate || !isChooseGoods"
                      @focus="inputFocus"
                    />
                    <div>个包裹</div>
                  </div>
                </el-radio>
                <el-radio :value="2">按商品总数生成</el-radio>
                <el-radio :value="3">按商品明细条数生成</el-radio>
              </el-radio-group>
              <el-button
                :disabled="!isCanCreate || !isChooseGoods"
                type="primary"
                class="ml-5"
                :loading="billNoLoading"
                @click="createBillNo"
                >生成</el-button
              >
            </div>
          </el-tooltip>
          <div v-if="billNoList.length > 0" class="flex">
            <div class="w-[90px] text-right">运单号</div>
            <div class="ml-4 flex-1">
              <div class="flex flex-wrap">
                <div
                  v-for="(item, index) in billNoList"
                  :key="index"
                  class="mb-2 mr-2"
                >
                  {{ item.kuaidinum }}
                </div>
              </div>
              <div>
                <span
                  v-print="printObj"
                  class="cursor-pointer text-blue-500 mr-2"
                >
                  打印面单
                </span>
                <span
                  class="cursor-pointer text-blue-500"
                  @click="repealBillNo"
                >
                  撤销单号
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 打印单号 -->
    <div style="width: 0; height: 0; overflow: hidden">
      <PrintBillNo id="print-box" :billNoList="billNoList" />
    </div>
  </div>
</template>
<style lang="scss" scoped>
.goods-table {
  padding: 0 20px;
  margin-bottom: 25px;
  min-height: 650px;
}
.tips {
  display: flex;
  align-items: center;
  padding: 6px 15px;
  border: 1px solid #c6e2ff;
  border-radius: 5px;
  background-color: #ecf5ff;
}
</style>
